<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('店铺商品列表')"/>
    <th:block th:include="include :: bootstrap-editable-css"/>
    <style>
        .wrap {
            position: relative;
        }

        .sm-mark {
            position: absolute;
            top: 0;
            left: 0;
            margin: 0;
        }

        .xs-mark {
            position: absolute;
            top: 0;
            left: 0;
            margin: 0;
        }

        .sm-mark:before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            border-style: solid;
            border-width: 16px;
            z-index: 1;
            border-color: rgba(206, 3, 5, .7) transparent transparent rgba(206, 3, 5, .7);
        }

        .xs-mark:before {
            content: "";
            position: absolute;
            top: 0;
            left: 0;
            border-style: solid;
            border-width: 8px;
            z-index: 1;
            border-color: rgba(206, 3, 5, .7) transparent transparent rgba(206, 3, 5, .7);
        }

        .img-sm-text {
            color: #FFF;
            display: inline-block;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
            font-size: 12px;
            text-transform: uppercase;
            width: 20px;
            text-align: center;
        }

        .img-xs-text {
            color: #FFF;
            display: inline-block;
            position: absolute;
            top: 0;
            left: 0;
            z-index: 1;
            font-size: 12px;
            text-transform: uppercase;
            width: 0;
            text-align: center;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 search-collapse">
            <form id="shop-product-form">
                <div class="select-list">
                    <ul>
                        <li>
                            <p style="width: 80px">商品名称： </p>
                            <input type="text" name="productName"/>
                        </li>
                        <li>
                            <p style="width: 80px">商品分类： </p>
                            <input type="hidden" name="categoryIdStr"/>
                            <input type="text" onclick="selectCategoryTree()" id="categoryName"
                                   placeholder="全部"/>
                        </li>
                        <li>
                            <p style="width: 80px">商品状态： </p>
                            <select name="isEnable" th:with="type=${@dict.getType('product_status')}">
                                <option value="">全部</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                        th:value="${dict.dictValue}"></option>
                            </select>
                        <li>
                            <p style="width: 80px">是否新品： </p>
                            <select name="isNew" th:with="type=${@dict.getType('is_new')}">
                                <option value="-1">全部</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                        th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li>
                            <p style="width: 80px">是否推荐： </p>
                            <select name="isRecommend" th:with="type=${@dict.getType('is_recommend')}">
                                <option value="-1">全部</option>
                                <option th:each="dict : ${type}" th:text="${dict.dictLabel}"
                                        th:value="${dict.dictValue}"></option>
                            </select>
                        </li>
                        <li class="select-time">
                            <p style="width: 80px">创建时间： </p>
                            <input type="text" class="time-input" placeholder="开始时间"
                                   name="params[beginTime]"/>
                            <span>-</span>
                            <input type="text" class="time-input" placeholder="结束时间"
                                   name="params[endTime]"/>
                        </li>
                        <li>
                            <a class="btn btn-primary btn-rounded btn-sm" onclick="$.table.search()"><i
                                    class="fa fa-search"></i>&nbsp;搜索</a>
                            <a class="btn btn-warning btn-rounded btn-sm" onclick="formReset()"><i
                                    class="fa fa-refresh"></i>&nbsp;重置</a>
                        </li>
                    </ul>
                </div>
            </form>
        </div>
        <div class="btn-group-sm" id="toolbar" role="group">
            <a class="btn btn-success" onclick="$.operate.add()" shiro:hasPermission="back:shopProduct:add">
                <i class="fa fa-plus"></i> 新增
            </a>
            <a class="btn btn-primary multiple disabled" onclick="multiEdit(1,1)">
                <i class="fa fa-check"></i> 批量上架
            </a>
            <a class="btn btn-danger multiple disabled" onclick="multiEdit(1,0)">
                <i class="fa fa-ban"></i> 批量下架
            </a>
            <!--<a class="btn btn-danger multiple disabled" onclick="$.operate.removeAll()">-->
                <!--<i class="fa fa-remove"></i> 删除-->
            <!--</a>-->
        </div>
        <div class="col-sm-12 select-table table-striped">
            <table id="bootstrap-table"></table>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-table-editable-js"/>
<script th:inline="javascript">
    const editFlag = [[${@permission.hasPermi('back:shopProduct:edit')}]];
    const removeFlag = [[${@permission.hasPermi('back:shopProduct:remove')}]];
    const productStatusDict = [[${@dict.getType('product_status')}]];
    const isRecommendDict = [[${@dict.getType('is_recommend')}]];
    const isNewDict = [[${@dict.getType('is_new')}]];
    const prefix = ctx + "back/shopProduct";

    $(function () {
        var options = {
            url: prefix + "/list",
            createUrl: prefix + "/add",
            updateUrl: prefix + "/edit/{id}",
            removeUrl: prefix + "/remove",
            sortName: "orderNum asc,createTime",
            height:600,
            sortOrder: "desc",
            modalName: "店铺商品",
            showColumns: true,
            paginationShowPageGo: true,
            clickToSelect: true,
            detailView: true,
            onExpandRow: function (index, row, $detail) {
                if (parseInt(row.hasAttribute) === 1) {
                    initChildTable(index, row, $detail);
                }
            },
            onLoadSuccess: function (data) {
                $.each(data.rows, function (index, row) {
                    if (parseInt(row.hasAttribute) === 0) {
                        $('.bootstrap-table').find('tr[data-index=' + index + ']').find('.detail-icon').hide();
                    }
                    if(data.rows.length<5 && index<3){
                        $('#bootstrap-table').bootstrapTable('expandRow',index);
                    }
                })
            },
            columns: [{
                checkbox: true
            },
                {
                    field: 'id',
                    title: 'ID',
                    visible:false
                },
                {
                    field: 'productId',
                    title: '商品ID',
                },
                {
                    field: 'productCategory',
                    title: '商品分类',
                    sortable: true
                },
                {
                    field: 'hasAttribute',
                    title: '是否有规格',
                    visible: false
                },
                // {
                //     field: 'attrCategoryName',
                //     title: '规格分类'
                // },
                {
                    field: 'productName',
                    title: '商品名称',
                    sortable: true
                },
                {
                    field: 'coverUrlThumb',
                    title: '封面图',
                    formatter: function (value, row, index) {
                        var imgHtml = "<img class='img-circle img-sm' data-height='%s' data-width='%s' data-target='%s'  style='border-radius: 0;' src='%s' data-src='%s'/>";
                        if(1== row.isPromotion){
                            imgHtml = "<img class='img-circle img-sm' data-height='%s' data-width='%s' data-target='%s'  style='border-radius: 0;border:3px solid red' src='%s' data-src='%s'/>"
                            return "<div class='wrap'>"+$.common.sprintf(imgHtml, 400, 'auto', 'self', value, row.coverUrl)+"<p class='sm-mark'><span class='img-sm-text'>促</span></p></div>";
                        }else{
                            return $.common.sprintf(imgHtml, 400, 'auto', 'self', value, row.coverUrl);
                        }
                    }
                },
                {
                    field: 'stock',
                    title: '总库存',
                    sortable: true
                },
                // {
                //     field: 'buyPrice',
                //     title: '平台价格',
                //     formatter: function (value, row, index) {
                //         var actions = [];
                //         actions.push('<label>成本价：</label><span style="font-weight: bold">' + value + '</span>');
                //         actions.push('<br/><label>建议卖价：</label><span style="font-weight: bold">' + row.price + '</span>');
                //         return actions.join('');
                //     }
                // },
                // {
                //     field: 'productPrice',
                //     title: '售价',
                //     sortable: true
                // },
                {
                    field: 'isNew',
                    title: '新品',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(isNewDict, value);
                    }
                },
                {
                    field: 'isRecommend',
                    title: '推荐',
                    sortable: true,
                    formatter: function (value, row, index) {
                        return $.table.selectDictLabel(isRecommendDict, value);
                    }
                },
                {
                    field: 'orderNum',
                    title: '排序',
                    sortable: true
                },
                {
                    field: 'isEnable',
                    title: '状态',
                    sortable: true,
                    formatter: function (value, item, index) {
                        return $.table.selectDictLabel(productStatusDict, value);
                    }
                },
                {
                    field: 'createTime',
                    title: '新增时间',
                    sortable: true
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<a class="btn btn-success btn-xs ' + editFlag + '" href="#" onclick="$.operate.edit(\'' + row.id + '\')"><i class="fa fa-edit">编辑</i></a> ');
                        // actions.push('<a class="btn btn-danger btn-xs ' + removeFlag + '" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\')"><i class="fa fa-trash"></i>删除</a>');
                        return actions.join('');
                    }
                }]
        };
        $.table.init(options);
    });

    function formReset() {
        $('input[name="categoryIdStr"]').val("");
        $.form.reset();
    }

    function onEditableSave(field, row,oldValue,$el) {
        let updateData = {};
        if(field == "productPrice"){
            var initVal = $el.html();
            var productPrice = parseFloat(row[field]);
            var buyPrice = parseFloat(row.buyPrice);
            if(productPrice<buyPrice){
                $.modal.alertError("售价不能低于成本价！");
                row.productPrice = initVal;
                $('#skuTable'+row.productId).bootstrapTable('updateRow', {index: row.rowId, row: row});
                return;
            }
            if(productPrice>buyPrice*2){
                $.modal.alertError("售价不能高于成本价两倍！");
                row.productPrice = initVal;
                $('#skuTable'+row.productId).bootstrapTable('updateRow', {index: row.rowId, row: row});
                return;
            }
        }
        updateData[field] = row[field]
        updateData.id = row.id;
        $.ajax({
            type: 'post',
            url: ctx + "back/shopProduct/editSku",
            data: updateData,
            dataType: 'json',
            async: false,
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $.modal.alertSuccess("修改成功");
                } else {
                    $("#skuTable"+row.productId).bootstrapTable('refresh');
                    $.modal.alertError(result.msg);
                }
            }
        });
    }

    function multiEdit(type, val) {
        var rows = $.table.selectFirstColumns();
        if (rows.length == 0) {
            $.modal.alertWarning("请至少选择一条记录");
            return;
        }
        let updateData = {
            ids: rows.join()
        };
        switch (parseInt(type)) {
            case 1:
                //批量上架/下架
                updateData.isEnable = val;
                break;
            default:
                $.modal.alertWarning("操作失败！");
                return;
        }
        $.ajax({
            type: 'post',
            url: ctx + "back/shopProduct/edit",
            data: updateData,
            dataType: 'json',
            async: false,
            success: function (result) {
                if (result.code == web_status.SUCCESS) {
                    $.modal.alertSuccess("操作成功！");
                } else {
                    $.modal.alertError(result.msg);
                }
                $.table.refresh();
            }
        });
    }

    //* 商品分类筛选*/
    function selectCategoryTree() {
        var categoryIdStr = $("input[name='categoryIdStr']").val();
        categoryIdStr = $.common.isEmpty(categoryIdStr) ? "0" :  $("input[name='categoryIdStr']").val();
        var url = ctx + "back/productCategory/selectTree/" + categoryIdStr;
        var options = {
            title: '商品分类筛选',
            width: "380",
            url: url,
            callBack: function (index, layero) {
                var body = layer.getChildFrame('body', index);
                if(parseInt(body.find('#treeId').val())!==0){
                    $('input[name="categoryIdStr"]').val(body.find('#treeId').val());
                }else{
                    $('input[name="categoryIdStr"]').val("");
                }
                $("#categoryName").val(body.find('#treeName').val());
                // var tree = layero.find("iframe")[0].contentWindow.$._tree;
                // let checkedNodes = tree.getCheckedNodes(true);
                // let categoryIdStr = "";
                // let categoryNameStr = "";
                // for (let i = 0; i < checkedNodes.length; i++) {
                //     categoryIdStr += checkedNodes[i].id + ",";
                //     categoryNameStr += checkedNodes[i].name + ",";
                // }
                // $('input[name="categoryIdStr"]').val(categoryIdStr.substring(0,categoryIdStr.length-1));
                // $('#categoryName').val(categoryNameStr.substring(0,categoryNameStr.length-1));
                layer.close(index);
                $.table.search();
            }
        };
        $.modal.openOptions(options);
    }

    initChildTable = function (index, row, $detail) {
        var cur_table = $detail.html('<table style="table-layout:fixed" id="skuTable'+row.productId+'"></table>').find('table');
        $(cur_table).bootstrapTable({
            url: prefix + "/skuList",
            method: 'post',
            sidePagination: "server",
            contentType: "application/x-www-form-urlencoded",   // 编码类型
            queryParams: {
                productId: row.productId
            },
            onEditableSave: onEditableSave,
            columns: [
                {
                    field: 'skuCode',
                    title: '商品条码',
                    formatter: function (value, row, index) {
                        var showText = value;
                        var searchArr = $('#shop-product-form').serializeArray();
                        for(let i=0;i<searchArr.length;i++){
                            if('skuCode' == searchArr[i].name && ''!=searchArr[i].value){
                                if(value.indexOf(searchArr[i].value)>-1){
                                    showText = '<span style="color: red;font-weight:bold">'+value+'</span>';
                                    break;
                                }
                            }
                        }
                        return showText;
                    }
                },
                {
                    field: 'productId',
                    title: '商品ID',
                    visible: false
                },
                {
                    field: 'coverUrl',
                    title: 'sku封面图',
                    formatter: function (value, row, index) {
                        if ($.common.isEmpty(value)) {
                            return "-"
                        } else {
                            var imgStr = $.common.sprintf("<img class='img-circle img-xs' data-height='%s' data-width='%s' data-target='%s'  style='border-radius: 0;' src='%s' data-src='%s'/>", 400, 'auto', 'self', value, value);
                            if(1== row.isPromotion){
                                imgStr = "<div class='wrap'>"
                                    +$.common.sprintf("<img class='img-circle img-xs' data-height='%s' data-width='%s' data-target='%s'  style='border-radius: 0;border:3px solid red' src='%s' data-src='%s'/>", 400, 'auto', 'self', value, value)
                                    +"<p class='xs-mark'></p></div>";
                            }
                            return imgStr;
                        }
                    }
                },
                {
                    field: 'skuJson',
                    title: 'SKU名称',
                    formatter: function (value, row, index) {
                        let skuName = "";
                        let skuJsonData = JSON.parse(value);
                        for (let i = 0; i < skuJsonData.length; i++) {
                            // skuName += skuJsonData[i].key + ":" + skuJsonData[i].value + ";"
                            skuName += skuJsonData[i].value
                        }
                        return skuName;
                    }
                },
                {
                    field: 'buyPrice',
                    title: '平台价格',
                    formatter: function (value, row, index) {
                        var actions = [];
                        actions.push('<label>成本价：</label><span style="font-weight: bold">' + value + '</span>');
                        actions.push('<br/><label>建议卖价：</label><span style="font-weight: bold">' + row.price + '</span>');
                        return actions.join('');
                    }
                },
                {
                    field: 'productPrice',
                    title: '销售价',
                    editable: {
                        type: 'text',
                        title: '销售价',
                        emptytext: "【销售价】不能为空",
                        validate: function (v) {
                            if ($.trim(v) == '') {
                                return '【销售价】不能为空!';
                            }
                            if (isNaN(v)) {
                                return '【销售价】必须是数字';
                            }
                            if (!(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v))) {
                                return '请输入正确的【销售价】';
                            }
                        }
                    }
                },
                {
                    field: 'stock',
                    title: '库存',
                },
                {
                    field: 'sale',
                    title: '店铺总销量',
                },
                // {
                //     field: 'lowStock',
                //     title: '预警库存',
                //     editable: {
                //         type: 'text',
                //         title: '预警库存',
                //         emptytext: "【预警库存】不能为空",
                //         validate: function (v) {
                //             if ($.trim(v) == '') {
                //                 return '【预警库存】不能为空!';
                //             }
                //             if (isNaN(v)) {
                //                 return '【预警库存】必须是数字';
                //             }
                //             if (!(/(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/.test(v))) {
                //                 return '请输入正确的【预警库存】';
                //             }
                //         }
                //     }
                // },
                {
                    field: 'isEnable',
                    title: '状态',
                    editable: {
                        type: 'select',
                        title: '状态',
                        source: [{
                            value: 1,
                            text: "在售"
                        }, {
                            value: 0,
                            text: "停售"
                        }]
                    }
                }]
        });
    };

</script>
</body>
</html>